package com.hong.fy_common_commomutil.common.helper;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper {

    //过期时间
    private static long tokenExpiration = 24*60*60*1000; //24小时
    //签名秘钥
    private static String tokenSignKey = "123456";

    //根据参数生成token
    public static String createToken(Integer userId, String userName) {
        String token = Jwts.builder() //JWT由三部分组成：header、payload、signature
                .setSubject("FY-USER") //主题
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) //过期时间
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey) //签名算法和签名秘钥
                .compressWith(CompressionCodecs.GZIP) //压缩方式
                .compact(); //生成token
        return token;
    }

    //根据token字符串得到用户id
    public static Integer getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null; //如果token为空,则返回null

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId;
    }

    //根据token字符串得到用户名称
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) return "";

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }

}

